package com.ljh.controller;


import com.ljh.pojo.Clazz;
import com.ljh.service.IClazzService;
import com.ljh.service.ITagService;
import com.ljh.vo.ClazzVo;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author lijiahao
 * @since 2021-09-25
 */
@RestController
@RequestMapping("/clazz")
public class ClazzController {

    @Autowired
    private IClazzService clazzService;
    @Autowired
    private ITagService tagService;

    @Value("${upload.dir}")
    private String realpath;

    @GetMapping
    public List<ClazzVo> listAll(){
        List<Clazz> clazzList = clazzService.list();
        ArrayList<ClazzVo> vos = new ArrayList<>();
        for (Clazz clazz : clazzList) {
            ClazzVo clazzVo = new ClazzVo();
            BeanUtils.copyProperties(clazz,clazzVo);
            clazzVo.setTag(tagService.getById(clazz.getTagId()));
            vos.add(clazzVo);
        }
        return vos;
    }

    @GetMapping("/{id}")
    public ClazzVo clazz(@PathVariable("id") int id){
        Clazz clazz = clazzService.getById(id);
        ClazzVo clazzVo = new ClazzVo();
        BeanUtils.copyProperties(clazz,clazzVo);
        clazzVo.setTag(tagService.getById(clazz.getTagId()));
        return clazzVo;
    }

//    @PutMapping
//    public String add(@RequestBody Clazz clazz){
//        clazzService.save(clazz);
//        return "添加成功";
//    }

    @PutMapping
    public String add(String name, MultipartFile file,Integer tagId) throws IOException {

        String newFilename= UUID.randomUUID().toString().replace("-","")+"."
                + FilenameUtils.getExtension(file.getOriginalFilename());
        System.out.println("=========>"+UUID.randomUUID().toString());
        file.transferTo(new File(realpath,newFilename));
        Clazz clazz = new Clazz();
        clazz.setName(name);
        clazz.setPath(newFilename);
        clazz.setTagId(tagId);
        clazzService.save(clazz);
        return "添加成功";
    }



}
